/*
* Copyright 2005-2008 Pulse Technologies. Tutti i diritti riservati.
*/
package org.obsidianrad.server.services.obj2db.decisioners;


import java.util.HashMap;

import org.obsidianrad.server.services.ObsModel;
import org.obsidianrad.server.services.user.context.IContextManager;
import org.obsidianrad.server.services.user.rolemanager.RoleManager;
import org.obsidianrad.utils.Constant.ObsidianOperations;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.context.SecurityContextHolder;

/**
 * 
 * @author Eligio Colutta
 * @version $Rev: 21 $
 * @lastautorcommit $Author: eliosh $
 * @lastdatecommit $Date: 2010-01-06 12:09:45 +0100(mer, 06 gen 2010) $
 */
public class GenericContextDecisioner implements IDecisioner {
	
	private RoleManager roleManager;
	
	/* (non-Javadoc)
	 * @see org.obsidianrad.server.services.obj2db.decisioners.IDecisioner#decide(org.obsidianrad.utils.Constant.ObsidianOperations, java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	public boolean decide(ObsidianOperations op, String reference){

		// result.setDetails( ((ObsidianUserDetails)user).getPreferences() );
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // UsernamePasswordAuthenticationToken
		GrantedAuthority[] authorities = authentication.getAuthorities();

		HashMap<String, Object> preferences = (HashMap<String, Object>) authentication.getDetails();
		Object active_context = preferences.get(IContextManager.CONTEXT_PARAM_KEY);
		if(active_context==null){
			active_context = 1;
		}

		// FIXME recupera il contesto attuale
		Integer contextID = (Integer) active_context;

		// costruisci il ruolo richiesto
		String requestedRole = roleManager.constructRole(reference, op, contextID);
		
		// controlla se il ruolo costruito esiste per questo utente, nella lista dei ruoli abilitati
		for(GrantedAuthority auth : authorities){
			if(auth.getAuthority().equals(requestedRole)){
				return true;
			}
		}

		return false;
	}

	/* (non-Javadoc)
	 * @see org.obsidianrad.server.services.obj2db.decisioners.IDecisioner#decide(org.obsidianrad.utils.Constant.ObsidianOperations, java.lang.Class)
	 */
	public boolean decide(ObsidianOperations op, Class<? extends ObsModel> reference){
		return decide(op, reference.getClass().getCanonicalName());
	}
	
	public RoleManager getRoleManager() {
		return roleManager;
	}

	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}
}
